package com.hkbigdata.window;

import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import javax.xml.bind.ValidationEvent;
import java.util.Arrays;


/**
 * @author liuanbo
 * @creat 2024-04-29-14:23
 * @see 2194550857@qq.com
 */
public class Flink09_Sliding_ProcessWindowFunction_Windows {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(1);

        SingleOutputStreamOperator<Tuple2<String, Integer>> flatMap = env.socketTextStream("hadoop102", 9999)
                .flatMap((String line, Collector<Tuple2<String, Integer>> out) -> {
                    Arrays.stream(line.split(",")).forEach(word -> out.collect(Tuple2.of(word, 1)));
                }).returns(Types.TUPLE(Types.STRING, Types.INT));

        flatMap.keyBy(data -> data.f0)
                .window(TumblingProcessingTimeWindows.of(Time.seconds(5)))
                .process(new ProcessWindowFunction<Tuple2<String, Integer>, Tuple2<String, Integer>, String, TimeWindow>() {
                    @Override
                    public void process(String key, Context context, Iterable<Tuple2<String, Integer>> elements, Collector<Tuple2<String, Integer>> out) throws Exception {
                        Integer sum = 0;
                        for (Tuple2<String, Integer> element : elements) {
                            sum += element.f1;
                        }
                        out.collect(Tuple2.of(key, sum));
                    }
                })
                .print();
        /**
         * aggregateFunction & reduce 1+2=3,3+4=7......只保留最终结果值
         * processfunction  1+2+3+4+5+6..... 只保留最终结果值
         */
        Integer[] arr = {1, 2, 4, 5, 6};
        env.execute();
    }
}
